<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案源环节-案源情况说明</title>
    <link rel="stylesheet" href="/layui/v10/layui.css">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <style>
        .clue-group {
            margin-bottom: 15px;
        }

        .clue-left,
        .clue-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .clue-label {
            white-space: nowrap;
        }

        .remove-btn {
            margin-left: 10px;
        }

    </style>
</head>

<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header"></div>
                <div class="layui-card-body">
                    <div id="aybzDiv" th:text="${aybz}" style="display:none"></div>
                    <!-- 线索案件列表  -->
                    <div id="ajDiv">
                        <div class="layui-tab-item layui-show">
                            <form class="layui-form" id="searchForm0">
                                <div class="layui-input-inline">
                                    <label for="jcajbh"></label>
                                    <input type="text" id="jcajbh" class="layui-input" autocomplete="off"
                                           placeholder="请输入案件编号">
                                </div>
                                <div class="layui-input-inline">
                                    <label for="nsrsbh"></label>
                                    <input type="text" id="nsrsbh" class="layui-input" autocomplete="off"
                                           placeholder="请输入纳税人识别号">
                                </div>
                                <div class="layui-input-inline">
                                    <label for="nsrmc"></label>
                                    <input type="text" id="nsrmc" class="layui-input" autocomplete="off"
                                           placeholder="请输入纳税人名称">
                                </div>
                                <div class="layui-input-inline">
                                    <label for="lasjTime"></label>
                                    <input type="text" readonly class="layui-input" id="lasjTime"
                                           placeholder="立案日期">
                                </div>
                                <div class="layui-input-inline">
                                    <label for="bz"></label>
                                    <select name="bz" id="bz">
                                        <option value="">是否录入线索</option>
                                        <option value="Y">已录入</option>
                                        <option value="N">未录入</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <button type="button" class="layui-btn" id="search">查询</button>
                                    <button type="button" class="layui-btn" id="resetBtn">重置</button>
                                </div>
                            </form>
                            <!-- 查询列 -->
                            <table class="layui-table" id="ajTable" lay-filter="ajTable"></table>
                        </div>
                    </div>
                    <!--线索信息录入-->
                    <div id="xsDiv" style="display: none">
                        <fieldset class="layui-elem-field layui-field-title">
                            <legend>线索信息录入</legend>
                        </fieldset>
                        <div class="layui-form"
                             style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap; margin-bottom: 12px;">
                            <div style="display: flex; align-items: center;">
                                <span style="margin-right: 6px; white-space: nowrap;">纳税人名称：</span>
                                <span id="nsrmcText" style="min-width: 200px; display: inline-block;"></span>
                            </div>

                            <div style="display: flex; align-items: center;margin-right: -90px;">
                                <span style="margin-right: 6px; white-space: nowrap;">立案时间：</span>
                                <span id="larqText" style="min-width: 180px; display: inline-block;"></span>
                            </div>

                            <div style="display: flex; align-items: center;">
                                <span style="margin-right: 6px; white-space: nowrap;">案件编号：</span>
                                <span id="ajbhText" style="min-width: 200px; display: inline-block;"></span>
                            </div>
                            <button type="button" class="layui-btn" id="addClueBtn">新增线索</button>
                            <button type="button" class="layui-btn" id="saveClueBtn">保存线索</button>
                            <button type="button" class="layui-btn" id="back">返回</button>
                        </div>
                        <!-- 录入容器 -->
                        <div id="editSection" style="display: block">
                            <input type="hidden" class="dataBz" name="dataBz" value="">
                            <input type="hidden" class="jcajxxuuid" name="jcajxxuuid" value="">
                            <div id="editContainer"></div>
                        </div>
                        <!-- 查看容器 -->
                        <div id="viewSection" style="display: none">
                            <input type="hidden" class="dataBz" name="dataBz" value="">
                            <input type="hidden" class="jcajxxuuid" name="jcajxxuuid" value="">
                            <div id="viewContainer"></div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="ajxxtool">
    {{#
    var btnText = "录入";
    var currentBz = 'N';

    if (aybz === 'jc' && d.jcbz) {
    currentBz = d.jcbz;
    } else if (aybz === 'sl' && d.slbz) {
    currentBz = d.slbz;
    } else if (aybz === 'ay' && d.bz) {
    currentBz = d.bz;
    }

    if (currentBz === "Y") {
    btnText = "查看";
    }
    }}
    <a class="layui-btn layui-btn-xs" lay-event="lrXs">{{ btnText }}</a>
</script>

<script src="/layui/v10/layui.js"></script>
<script src="/js/core.util.js"></script>
<script th:inline="none">
    // 获取token
    var token = CoreUtil.getData("access_token");
    // 地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    var upload = layui.upload;
    var element = layui.element;

    let tableIns1;

    let la_startTime = null;
    let la_endTime = null;

    let aybz = null;

    // 案源标志 案源环节 ay  检查环节  jc  审理环节 sl
    $(function () {
        const url = new URL(window.location.href);
        // 仅当 aybz 为 null/undefined 时，才根据 URL 路径推断默认值
        aybz = url.searchParams.get("aybz");
        if (aybz == null) {
            if (window.location.pathname.includes("/jcayqksm")) {
                aybz = "jc"; // 检查环节默认 "jc"
            } else if (window.location.pathname.includes("/slayqksm")) {
                aybz = "sl"; // 审理环节默认 "sl"
            } else {
                aybz = "ay"; // 其他情况默认 "ay"
            }
        }

        console.log("aybz:", aybz); // 调试输出
        window.parentAybz = aybz;
    });
    // // 渲染表格前设置模板全局变量
    // window.parentAybz = aybz; // 挂载到全局

    // 案件DIV
    const ajDiv = $("#ajDiv");
    // 线索DIV
    const xsDiv = $("#xsDiv");

    let editSection = $('#editSection');
    let viewSection = $('#viewSection');

    let clue_group = $('.clue-group');

    let editContainer = $('#editContainer');

    let viewContainer = $('#viewContainer');


    layui.use(['table', 'layer', 'laydate', 'upload', 'element'], function () {

        console.log("进入方式:", aybz)

        // 委托方式删除动态生成的线索项
        $('#editContainer').on('click', '.remove-btn', function () {
            $(this).closest('.clue-group').remove();
        });

        // 委托方式删除动态生成的线索项
        $('#viewContainer').on('click', '.remove-btn', function () {
            $(this).closest('.clue-group').remove();
        });

        // 新增线索
        $('#addClueBtn').click(function () {
            const dataBz = $('.dataBz').val().trim();

            // 获取当前线索组的数量（应该根据对应的容器来计算）
            let currentCount;
            if (dataBz === "Y") {
                currentCount = $('#viewContainer .clue-group').length;
            } else {
                currentCount = $('#editContainer .clue-group').length;
            }

            // 新线索的索引应该是当前数量+1
            const index = currentCount + 1;

            const newClueHtml = `
    <div class="layui-row clue-group" data-index="${index}">
        <div class="layui-col-xs6 clue-left">
            <label class="clue-label">线索${index}：</label>
            <input type="text" name="clue${index}" required lay-verify="required" placeholder="请输入案源线索内容" class="layui-input">
            <input type="text" name="source${index}" placeholder="请输入检查环节备注" class="layui-input" style="margin-left: 10px">
        </div>
        <div class="layui-col-xs6 clue-right">
            <div class="layui-form clue-accuracy" style="margin-left: 20px">
                <span style="white-space: nowrap; margin-right: 8px;">线索准确度：</span>
                <input type="checkbox" name="accuracy${index}[]" title="优" disabled>
                <input type="checkbox" name="accuracy${index}[]" title="良" disabled>
                <input type="checkbox" name="accuracy${index}[]" title="差" disabled>
            </div>
            <input type="text" name="remark${index}" placeholder="请输入审理备注" class="layui-input" style="width: 400px">
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm remove-btn">删除</button>
        </div>
    </div>`;

            if (dataBz === "N") {
                $('#editContainer').append(newClueHtml);
            } else {
                $('#viewContainer').append(newClueHtml);
            }

            // 重新渲染表单
            layui.form.render();

            // 对新插入的项执行权限控制
            const $newGroup = dataBz === "N" ? $('#editContainer .clue-group').last() : $('#viewContainer .clue-group').last();
            applyPermissionControl($newGroup, aybz);
        });
        // 立案时间
        laydate.render({
            elem: '#lasjTime'
            , type: 'date'
            , range: '~'
            , done: function (value) {
                if (value !== null && value !== undefined && value !== "") {
                    la_startTime = value.split("~")[0];
                    la_endTime = value.split("~")[1];
                } else {
                    la_startTime = null;
                    la_endTime = null;
                }
            }
        });
        // 案件列表
        tableIns1 = table.render({
            elem: '#ajTable'
            , loading: false
            , page: true //开启分页
            , contentType: 'application/json'
            , headers: {"authorization": token}
            , where: {"aybz": aybz}
            , url: '/ayhj/ayqksm/queryJcayqksmTable' //数据接口
            , method: 'POST'
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                    "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                }
            }
            , cols: [
                [
                    {field: 'jcajxxuuid', title: '主键', width: 100, hide: true},
                    {field: 'jcajbh', title: '案件编号', width: 200, align: "center", sort: true},
                    {field: 'ajmc', title: '案件名称', width: 380, align: "center", sort: true},
                    {field: 'ajztmc', title: '系统状态', width: 180, align: "center", sort: true},
                    {field: 'nsrsbh', title: '纳税人识别号', width: 200, align: "center", sort: true},
                    {field: 'nsrmc', title: '纳税人名称', width: 300, align: "center", sort: true},
                    {
                        field: 'larq',
                        title: '立案日期',
                        width: 140,
                        align: "center",
                        sort: true,
                        templet: function (d) {
                            if (!d.larq) {
                                return '';
                            }
                            return layui.util.toDateString(d.larq, 'yyyy-MM-dd');
                        }
                    },
                    {toolbar: '#ajxxtool', title: '操作', width: 100, align: 'center', fixed: 'right'}
                ]
            ]
            , toolbar: '#toolbar',
            done: function (res, curr, count) {
                // 把 aybz 注入到每一行数据中
                const currentAybz = aybz; // 或 'jc', 'sl'，看你哪里来
                res.data.forEach(row => {
                    row.aybz = currentAybz;
                });
            }
        });

        //操作
        table.on('tool(ajTable)', function (obj) {
            const data = obj.data;
            switch (obj.event) {
                case 'lrXs':
                    if (data.bz === "N") {
                        // === 录入模式 ===
                        editSection.show();
                        viewSection.hide();
                        editContainer.empty(); // 清空录入区
                        openXsDiv(data); // 弹窗等处理
                        // 自动新增第一条线索
                        addClueItem(editContainer, aybz);
                    } else {
                        // 进入查看模式
                        editSection.hide();
                        viewSection.show();
                        openXsDiv(data)
                        const jcajxxuuid = data.jcajxxuuid;
                        CoreUtil.sendPost("/ayhj/ayqksm/queryAyqksmXs", {jcajxxuuid}, function (res) {
                            const clueList = res.data || [];
                            const viewContainer = document.getElementById("viewContainer");
                            viewContainer.innerHTML = ""; // 清空查看内容
                            clueList.forEach((clue, index) => {
                                const groupHtml = `
<div class="layui-row clue-group" data-index="${index + 1}">
    <div class="layui-col-xs6 clue-left">
        <label class="clue-label">线索${index + 1}：</label>
        <input type="text" name="clue${index + 1}" value="${clue.clue || ''}" class="layui-input" >
        <input type="text" name="source${index + 1}" value="${clue.source || ''}" class="layui-input" style="margin-left: 10px">
    </div>
    <div class="layui-col-xs6 clue-right">
        <div class="layui-form clue-accuracy" style="margin-left: 20px">
            <span style="white-space: nowrap; margin-right: 8px;">线索准确度：</span>
            <input type="checkbox" name="accuracy${index + 1}[]" title="优" ${clue.accuracy && clue.accuracy.includes("优") ? "checked" : ""}>
            <input type="checkbox" name="accuracy${index + 1}[]" title="良" ${clue.accuracy && clue.accuracy.includes("良") ? "checked" : ""}>
            <input type="checkbox" name="accuracy${index + 1}[]" title="差" ${clue.accuracy && clue.accuracy.includes("差") ? "checked" : ""}>
        </div>
        <input type="text" name="remark${index + 1}" value="${clue.remark || ''}" class="layui-input" style="width: 400px">
        <button type="button" class="layui-btn layui-btn-danger layui-btn-sm remove-btn">删除</button>
    </div>
</div>`;
                                viewContainer.insertAdjacentHTML("beforeend", groupHtml);
                                // 对新添加的线索组应用权限控制
                                const $group = $(viewContainer).find('.clue-group').last();
                                applyPermissionControl($group, aybz);
                            });
                            layui.form.render();
                        });
                    }
                    break;
            }
        });

        // 案件查询
        $("#search").click(function () {
            //这里以搜索为例
            doSearch();
        });

        // 保存线索
        $("#saveClueBtn").click(function () {
            const clueList = [];
            const clueGroups = document.querySelectorAll('.clue-group');

            // 先拿到ID值
            const dataBz = $('.dataBz').val().trim();
            let jcajxxuuid;

            if (dataBz === "Y") {
                jcajxxuuid = $('#viewSection .jcajxxuuid').val();
            } else {
                jcajxxuuid = $('#editSection .jcajxxuuid').val();
            }

            console.log("保存:jcajxxuuid", jcajxxuuid); // 这就是你要的uuid值
            console.log("保存:aybz", aybz); // 这就是你要的uuid值

            clueGroups.forEach(group => {
                const bh = group.getAttribute('data-index');
                const clueInput = group.querySelector(`input[name="clue${bh}"]`);
                const clue = clueInput && clueInput.value ? clueInput.value.trim() : undefined;

                const sourceInput = group.querySelector(`input[name="source${bh}"]`);
                const source = sourceInput && sourceInput.value ? sourceInput.value.trim() : undefined;

                const remarkInput = group.querySelector(`input[name="remark${bh}"]`);
                const remark = remarkInput && remarkInput.value ? remarkInput.value.trim() : undefined;

                const accuracyInputs = group.querySelectorAll(`input[name="accuracy${bh}[]"]:checked`);
                const accuracy = Array.from(accuracyInputs).map(i => i.title).join(',');

                if (clue) {
                    clueList.push({
                        jcajxxuuid,    // 加上ID
                        bh,
                        aybz,
                        clue,
                        source,
                        remark,
                        accuracy
                    });
                }
            });

            console.log("结构化线索数据：", clueList);

            if (clueList.length === 0) {
                clueList.push({
                    jcajxxuuid,
                    bh: "N"
                })
            }

            // 调接口提交
            CoreUtil.sendPost("/ayhj/ayqksm/saveAyqksmXs", clueList, function (res) {
                layer.msg(res.msg, {time: 1000}, function () { // time: 提示显示时间（毫秒）
                    // 提示消失后回调刷新
                    window.location = window.location;
                });
                doSearch(); // 如果需要立即执行搜索，保留此行
            });
        });

        //返回
        $("#back").click(function () {
            backAjdiv();
            doSearch();
        });
    });

    function openXsDiv(data) {
        xsDiv.show();
        ajDiv.hide();
        editSection.find('.dataBz').val(data.bz);
        editSection.find('.jcajxxuuid').val(data.jcajxxuuid);
        viewSection.find('.dataBz').val(data.bz);
        viewSection.find('.jcajxxuuid').val(data.jcajxxuuid);
        $(".jcajxxuuid").val(data.jcajxxuuid)
        $(".dataBz").val(data.bz)
        $("#nsrmcText").text(data.nsrmc);
        let larq = data.larq
        if (larq.includes(" ")) {
            larq = larq.split(" ")[0];
        }
        $("#larqText").text(larq);
        $("#ajbhText").text(data.jcajbh);
    }

    function backAjdiv() {
        ajDiv.show();
        xsDiv.hide();
        $("#nsrmcText").text("");
        $("#larqText").text("");
        $("#ajbhText").text("");

        // 获取所有线索分组
        const $allGroups = clue_group;

        // 如果有多个分组，移除除了第一个的分组
        if ($allGroups.length > 1) {
            $allGroups.slice(1).remove();
        }

        // 清空第一个分组中的输入值和 checkbox 选中状态
        const $firstGroup = $allGroups.first();
        $firstGroup.find('input[type="text"]').val('');
        $firstGroup.find('input[type="checkbox"]').prop('checked', false);

        // 同时清除隐藏字段（如 uuid）
        $('#jcajxxuuid').val('');

        // 如果有权限控制，也重新应用一次
        const aybz = $('#aybzDiv').text().trim();
        applyPermissionControl($firstGroup, aybz);

        // 重新渲染 layui（用于复选框状态更新）
        layui.form.render();

    }

    function applyPermissionControl($group, aybz) {
        console.log("开关aybz:", aybz);
        const $clueInput = $group.find('input[name^="clue"]');
        const $sourceInput = $group.find('input[name^="source"]');
        const $remarkInput = $group.find('input[name^="remark"]');
        const $accuracyCheckboxes = $group.find('input[type="checkbox"]');
        const $deleteBtn = $group.find('.remove-btn');

        // 重置所有状态
        $group.find('input').prop('readonly', true).prop('disabled', true);
        $deleteBtn.hide();

        // 根据状态开放权限
        if (aybz === 'ay') {
            $clueInput.prop('readonly', false).prop('disabled', false);
            $deleteBtn.show();
        } else if (aybz === 'jc') {
            $sourceInput.prop('readonly', false).prop('disabled', false);
        } else if (aybz === 'sl') {
            $accuracyCheckboxes.prop('disabled', false);
            $remarkInput.prop('readonly', false).prop('disabled', false);
        }

        // 重新渲染表单
        layui.form.render();
    }

    // 封装新增线索函数（根据传入容器和data.bz判断插入内容）
    function addClueItem($container, dataBz) {
        var index = $container.find('.clue-group').length + 1;

        var newClueHtml = `
    <div class="layui-row clue-group" data-index="${index}">
        <div class="layui-col-xs6 clue-left">
            <label class="clue-label">线索${index}：</label>
            <input type="text" name="clue${index}" required lay-verify="required" placeholder="请输入案源线索内容" class="layui-input" style="width: 500px">
            <input type="text" name="source${index}" placeholder="请输入检查环节备注" class="layui-input" style="width: 500px;">
        </div>
        <div class="layui-col-xs6 clue-right">
            <div class="layui-form clue-accuracy" style="margin-left: 20px">
                <span style="white-space: nowrap; margin-right: 8px;">线索准确度：</span>
                <input type="checkbox" name="accuracy${index}[]" title="优" disabled>
                <input type="checkbox" name="accuracy${index}[]" title="良" disabled>
                <input type="checkbox" name="accuracy${index}[]" title="差" disabled>
            </div>
            <input type="text" name="remark${index}" placeholder="请输入备注" class="layui-input" style="width: 400px">
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm remove-btn">删除</button>
        </div>
    </div>`;

        $container.append(newClueHtml);

        // 根据权限控制字段处理可编辑状态
        applyPermissionControl($container.find('.clue-group').last(), dataBz);

        // 渲染 checkbox 样式
        layui.form.render();
    }


    //查询方法
    function doSearch() {
        tableIns1.reload({
            contentType: 'application/json'
            , headers: {"authorization": token}
            , where: { //设定异步数据接口的额外参数，任意设
                jcajbh: $("#jcajbh").val(),
                nsrmc: $("#nsrmc").val(),
                nsrsbh: $("#nsrsbh").val(),
                la_startTime: la_startTime,
                la_endTime: la_endTime,
                bz: $("#bz").val(),
                aybz: aybz
            }
            , url: '/ayhj/ayqksm/queryJcayqksmTable' //数据接口
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    }

</script>

</body>
</html>